import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
/* 
  封装一个函数，判断是否含有登录中存在的地址
*/
import store from '@/store'
function hasUrl(url: any, next: any) {
  let result =  store.getters.getUserInfo.menus_url.some((item: any) => item == url)
  console.log(result,'权限地址');
  
  if (result) {
    next()
    console.log(1111);
    
  } else {
    next('/home')
    console.log(2222);
  }
};
export const indexRouter = [
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    }
    ,
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl('/menu', next)
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    }
    ,
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl('/role', next)
    }
  },
  {
    path: '/admin',
    component: () => import('../views/admin/admin.vue'),
    meta: {
      title: '管理员管理'
    }
    ,
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl('/admin', next)
    }
  }
]
const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    component: () => import('../page/login.vue')
  },
  {
    path: '/index',
    component: () => import('../page/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue'),
      },
      ...indexRouter,
      {
        path: '',
        redirect: '/home'
      }]
  },
  {
    path: '',
    redirect: '/index'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 全局登录拦截
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    next()
    return
  }
  if (sessionStorage.getItem('userinfo')) {
    next()
    return
  }
  next('login')
})
export default router
